package com.dahuyou.netty.auth.server;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

@ChannelHandler.Sharable
public class AuthFilter extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("AuthFilter.channelRead 授权filter执行啦（一次性，用完就删除）！！！");
        try {
            // 如果是授权消息则处理，且必须是授权消息
            if (msg != null && msg.toString().startsWith("auth")) {
                if (msg.toString().endsWith("admin")) {
                    System.out.println("auth success!");
                    ctx.writeAndFlush("auth success!\r\n");
                } else {
                    System.out.println("授权失败啦!");
                    ctx.close();
                }
            } else {
                System.out.println("第一条消息必须是授权消息!");
                ctx.close();
            }
        } catch (Exception e) {
            System.out.println("e: " + e);
        } finally {
            // 一次性的，用完就删除
            ctx.pipeline().remove(this);
        }
        super.channelRead(ctx, msg);
    }
}
